﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonLib;
using System.Data.Common;
using DBHelperLib;

namespace CommonDAL
{
    public abstract class DataMapperL<TUniqueKey, TBusinessEntity, TDataEntity, TLazyEntity> :
        DataMapper<long, TUniqueKey, TBusinessEntity, TDataEntity, TLazyEntity>
        where TUniqueKey : struct
        where TBusinessEntity : class, IBusinessEntity<TUniqueKey>
        where TDataEntity : class, IDataEntityL<TUniqueKey, TBusinessEntity>, TBusinessEntity
        where TLazyEntity : LazyDataEntity<long, TUniqueKey, TBusinessEntity, TDataEntity>, TBusinessEntity
    {
        public DataMapperL(DBHelper helper) : base(helper)
        {
        }

        protected override void SetIdentityParameters(long identity)
        {
            DbHelper.Command.Parameters.Add(
                DbHelper.CreateParameter("@" + IdentityColumnName, identity));
        }

        protected override ToDataObjectMapper CreateToDataObjectMapper()
        {
            return CreateToDataObjectMapperL();
        }

        protected abstract class ToDataObjectMapperL : ToDataObjectMapper
        {
            private int _identityOrd = -1;

            protected override DataMapper<long, TUniqueKey, TBusinessEntity, TDataEntity, TLazyEntity> DataMapper
            {
                get { return LDataMapper; }
            }

            protected abstract DataMapperL<TUniqueKey, TBusinessEntity, TDataEntity, TLazyEntity> LDataMapper { get; }

            protected override void SetIdentityOrdinals(DbDataReader reader)
            {
                _identityOrd = reader.GetOrdinal(LDataMapper.IdentityColumnName);
            }

            protected override long MapIdentity(DbDataReader reader)
            {
                return reader.GetInt64(_identityOrd);
            }
        }

        protected abstract string IdentityColumnName { get; }
        protected abstract ToDataObjectMapperL CreateToDataObjectMapperL();
    }
}
